package com.basil.gym.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.basil.gym.constants.RedisConstants;
import com.basil.gym.pojo.entity.User;
import com.basil.gym.pojo.query.UserQuery;
import com.basil.gym.service.IUserService;
import com.basil.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Basil
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    public Result list() {
        return Result.ok(userService.list());
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(UserQuery userQuery) {
        System.out.println(userQuery);
        IPage<User> page = userService.selectByPage(userQuery);
        return Result.ok(page);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        userService.removeBatchByIds(Arrays.asList(ids));
        return Result.ok("批量删除成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, user.getAvatar());
        userService.updateById(user);
        return Result.ok("修改成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, user.getAvatar());
        userService.save(user);
        return Result.ok("添加成功");
    }
}

